package com.lwh.videopicplayer;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 */
public class MainActivity extends AppCompatActivity {

    private Context mContext;
    private static final int PERMISSION_WRITE_EXTERNAL_REQUEST_CODE = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_play);

        mContext = this;

        if (Build.VERSION.SDK_INT >= 23) {
            /*boolean result = Settings.canDrawOverlays(mContext);

            if (!result) {
                //没有悬浮窗权限,去开启悬浮窗权限
                showOverLayComfirmDialog();
            }else{*/
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    // 请求读写权限
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_WRITE_EXTERNAL_REQUEST_CODE);
                } else {
                    showListDialog();
                }
            /*}*/
        }else {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                // 请求读写权限
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_WRITE_EXTERNAL_REQUEST_CODE);
            } else {
                showListDialog();
            }
        }




    }

    //申请悬浮窗权限返回
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (Build.VERSION.SDK_INT >= 23) {
            boolean result = Settings.canDrawOverlays(mContext);

            if (!result) {
                showOverLayComfirmDialog();
            }else{
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    // 请求读写权限
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_WRITE_EXTERNAL_REQUEST_CODE);
                } else {
                    showListDialog();
                }
            }
        }else{
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                // 请求读写权限
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_WRITE_EXTERNAL_REQUEST_CODE);
            } else {
                showListDialog();
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case PERMISSION_WRITE_EXTERNAL_REQUEST_CODE: {
                // 检查授权结果
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    showListDialog();
                } else {
                    Toast.makeText(mContext, "获取授权失败！请重新进入并且授权！", Toast.LENGTH_LONG).show();
                    finish();
                }
                break;
            }
        }
    }



    private void showListDialog() {

        if (getCurrentBranch() != null && getCurrentBranch().equals("") == true) {

            final String[] items = getResources().getStringArray(R.array.branch_office);
            // 创建对话框构建器
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);

            // 设置对话框标题和项
            builder.setTitle("请选择安装的支局")
                    .setItems(items, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            setCurrentBranch(items[which]);
                            Toast.makeText(mContext, "已成功设置支局为：" + items[which], Toast.LENGTH_LONG).show();

                            Intent it = new Intent(mContext, PlayActivity.class);
                            it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            mContext.startActivity(it);
                            finish();
                        }
                    });

            // 创建并显示对话框
            AlertDialog dialog = builder.create();
            dialog.show();
        }else{
            Intent it = new Intent(mContext, PlayActivity.class);
            it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mContext.startActivity(it);
            finish();
        }
    }

    public void showOverLayComfirmDialog(){
        AlertDialog.Builder builder= new AlertDialog.Builder(mContext);
        builder.setTitle("提示");
        builder.setMessage("需要获取悬浮窗权限，请授权！");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                try {
                    Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                    startActivityForResult(intent, 101);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        builder.show();
    }

    public void setCurrentBranch(String branch){
        SharedPreferences mSharedPreferences = mContext.getSharedPreferences("Config", Context.MODE_PRIVATE);
        mSharedPreferences.edit().putString("persist.sys.branch", branch).commit();
    }

    public String getCurrentBranch(){
        SharedPreferences mSharedPreferences = mContext.getSharedPreferences("Config", Context.MODE_PRIVATE);
        String branch = mSharedPreferences.getString("persist.sys.branch","");
        return branch;
    }

}
